﻿using K9Nano.Authorization;
using K9Nano.Dependency;
using K9Nano.Domain.Entities;
using K9Nano.Mapping;
using Microsoft.EntityFrameworkCore;

namespace K9Nano.Application.Authentication;

public abstract class PermissionAppServiceBase<TRole, TRolePermission, TDbContext>(TDbContext db, IPermissionCatalog permissionCatalog)
    : IPermissionAppService, IScopedDependency
    where TRolePermission : RolePermissionBase<TRole>
    where TRole : RoleBase
    where TDbContext : DbContext
{
    /// <inheritdoc/>
    public IEnumerable<Permission> GetAllPermissions()
    {
        return permissionCatalog.Permissions;
    }

    /// <inheritdoc/>
    public async Task<IEnumerable<RoleDto>> GetRolesByPermissionAsync(string permission, CancellationToken cancellation = default)
    {
        var roles = await db.Set<TRolePermission>().Include(a => a.Role)
            .AsNoTracking()
            .Where(a => a.Permission == permission)
            .Select(a => a.Role)
            .ToListAsync(cancellation);
        if (!roles.Any())
        {
            return [];
        }
        var result = MappingHelper.Mapper.Map<List<RoleDto>>(roles);
        return result;
    }
}
